<?php

/**
 * 数据库操作
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-01
 */

namespace fw\db;

class DB
{
    public static $dbh = null;

    private static $_conf = [
        'host'    => '127.0.0.1',
        'port'    => '3306',
        'dbname'  => '',
        'user'    => 'root',
        'pwd'     => '',
        'charset' => 'utf8',
    ];

    public static function conn($conf = [])
    {
        if (is_null(self::$dbh)) {
            self::$_conf = array_merge(self::$_conf, $conf);
            $conf = self::$_conf;

            try {
                $dsn = "mysql:host={$conf['host']};port={$conf['port']};dbname={$conf['dbname']}";
                self::$dbh = new \PDO($dsn, $conf['user'], $conf['pwd'], [\PDO::MYSQL_ATTR_INIT_COMMAND => "set names {$conf['charset']}"]);
                self::$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            } catch (\PDOException $e) {
                $msg = 'Connection failed: ' . $e->getMessage();
                throw new \Exception($msg);
            }
        }

        return self::$dbh;
    }

    /**
     * 直接执行 SQL-SELECT 语句，返回结果数组。
     *
     * @param string $sql  SQL语句
     * @param array  $prep prepare 参数
     *
     * @return array
     */
    public static function query($sql, $prep = [])
    {
        if (!empty($prep)) {
            $stmt = self::$dbh->prepare($sql);
            $stmt->execute($prep);
            $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            $stmt = self::$dbh->query($sql);
            $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        }

        return $rows;
    }

    /**
     * 直接执行 SQL-SELECT 语句，返回一条记录。
     *
     * @param string $sql  SQL语句
     * @param array  $prep prepare 参数
     *
     * @return array
     */
    public static function queryRow($sql, $prep = [])
    {
        if (!empty($prep)) {
            $stmt = self::$dbh->prepare($sql);
            $stmt->execute($prep);
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        } else {
            $stmt = self::$dbh->query($sql);
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        }

        return $row;
    }

    /**
     * 直接执行SQL-insert/sql-update 语句，返回影响行数。
     *
     * @param string $sql  SQL语句
     * @param array  $prep prepare 参数
     *
     * @return int
     */
    public static function execute($sql, $prep = [])
    {
        if (!empty($prep)) {
            $stmt = self::$dbh->prepare($sql);
            $stmt->execute($prep);
            $affected_rows = $stmt->rowCount();
        } else {
            $affected_rows = self::$dbh->exec($sql);
        }

        return $affected_rows;
    }

    public static function table($tblName)
    {
        $quick = new Quick();
        $quick->table($tblName);

        return $quick;
    }
}
